from feedparser import parse
from sys import argv
import urllib, datetime

def main(blogURL, svnURL):
	blogFile=urllib.URLopener().open(blogURL)
	blogRSS=parse(blogFile.read())
	blogFile.close()

	svnFile=urllib.URLopener().open(svnURL)
	svnRSS=parse(svnFile.read())
	svnFile.close()
	merge(blogRSS, svnRSS)

def merge(rss1, rss2):
	inx = [0,0]
	done = [False, False]
	feeds = [rss1, rss2]
	d = None
	exit = False

	day = datetime.timedelta(1)

	# find first date
	for f in feeds:
		if (d == None):
			d = f['entries'][0]['updated_parsed']
		elif d < f['entries'][0]['updated_parsed']:
			d = f['entries'][0]['updated_parsed']

	d = datetime.date(d[0], d[1], d[2])
	
	print """<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="rssmerge.css"/>
</head>
<body>"""
	print "<table>"
	print "<tr>"
	for f in feeds:
		print "<th class='titles'>"+f['feed']['subtitle']+"</th>"
	print "</tr>\n"

	while (not exit):
		col = -1
		for i in range(len(feeds)):
			while ( not done[i] and sameDay(feeds[i]['entries'][inx[i]]['updated_parsed'], d) ):
				if (col == -1):
					print "<tr><th class='date' colspan=\""+`len(feeds)`+"\">"+d.strftime("%Y-%m-%d")+"</th></tr>"
					print "<tr>"
				if (col < i):
					print "<td></td>"*(i-col-1)
					print "<td>"
				col = i
				print "<h1>"+feeds[i]['entries'][inx[i]]['title']+"</h1>"
				print "<p>"+feeds[i]['entries'][inx[i]]['description']+"</p>"
				inx[i] = inx[i]+1
				if (not len(feeds[i]['entries'])>inx[i]):
					done[i] = True
			if (i == col):
				print "</td>"
		if (col != -1):
			print "</tr>\n"

		d = d - day

		exit = True
		for e in done:
			if e == False:
				exit = False
				break
	print "</table>"
	print """</body>
</html>"""

def sameDay(d1, d2):
	return d1[0] == d2.year and d1[1] == d2.month and d1[2] == d2.day

if __name__=='__main__':
	if (len(argv) < 2):
		print "Usage rssmerge.py <blogurl> <svnurl>"
	else:
		main(argv[1], argv[2])
